package com.bci.internal.engine.bcibpmengine.listener;



import com.bci.internal.engine.bcibpmengine.utils.ConstantUtils;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.util.Objects;

/**
 * 会签监听器
 *
 * @author jzwu
 * @since 2021/4/10 0010
 */

public class SignListener implements TaskListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(SignListener.class);

    @Override
    public void notify(DelegateTask delegateTask) {
        //获取执行id
        String exId = delegateTask.getExecutionId();
        /* 获取任务id和任务名称 */
        String taskId = delegateTask.getId();
        String name = delegateTask.getName();
        //获取流程参数pass，会签人员完成自己的审批任务时会添加流程参数pass，false为拒绝，true为同意
        ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
        RuntimeService runtimeService = engine.getRuntimeService();
        Integer pass = (Integer) runtimeService.getVariable(exId, ConstantUtils.PASS);
        Integer countResult = (Integer) runtimeService.getVariable(exId, ConstantUtils.COUNT_RESULT);
        /* 获取已经完成人数，所有审批人数  */
        Integer complete = (Integer) runtimeService.getVariable(exId, "nrOfCompletedInstances");
        Integer all = (Integer) runtimeService.getVariable(exId, "nrOfInstances");
        if (Objects.equals(pass, 1) && (countResult == 0)) {
            /* 只要有一个人不通过将则总监节点全部不通过返回【自评】节点  */
            runtimeService.setVariable(exId, "nrOfCompletedInstances", all);
            runtimeService.setVariable(exId, "result", "N");
        } else if (Objects.equals(pass, 0) && (countResult == 0)) {
            /* 说明都完成了并且没有人拒绝将流程跳转到【总经理】节点 */
            if ((complete + 1) / all == 1) {
                runtimeService.setVariable(exId, "result", "Y");
            }
        }
    }
}